package com.service;

import com.bean.PlanInfo;
import com.bean.other.MetaInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.PlanInfoMapper;
import com.mapper.repository.PlanInfoRepository;
import com.service.impl.PlanInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class PlanInfoServiceImpl implements PlanInfoService {

    @Autowired
    private PlanInfoRepository planInfoRepository;

    @Autowired
    private PlanInfoMapper planInfoMapper;

    @Override
    public String insert(PlanInfo planInfo) {
        //int count= (int) planInfoRepository.count();
        int count= planInfoRepository.countByCreator(planInfo.getCreator());
        planInfo.setId(UUID.randomUUID().toString());
        planInfo.setCreatetime(LocalDateTime.now());
        planInfo.setSortnum(count);
        planInfoRepository.save(planInfo);
        return "新增成功";
    }

    @Override
    public String update(PlanInfo planInfo) {
        planInfo.setUpdatetime(LocalDateTime.now());
        planInfoRepository.save(planInfo);
        return "更新成功";
    }

    @Override
    public String delete(PlanInfo planInfo) {
        planInfoRepository.delete(planInfo);
        return "删除成功";
    }

    @Override
    public PageInfo<PlanInfo> select(PlanInfo planInfo, MetaInfo metaInfo) {
        //PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize());
        PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize(),"sortnum");
        List<PlanInfo> list=planInfoMapper.select(planInfo);
        PageInfo<PlanInfo> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PlanInfo get(String id) {
        Optional<PlanInfo> optional=planInfoRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public String sort(List<PlanInfo> list, MetaInfo metaInfo) {
        int start =(metaInfo.getPage()-1)*metaInfo.getPage();
        for(PlanInfo planInfo:list){
            planInfo.setSortnum(start);
            start++;
        }
        planInfoRepository.saveAll(list);
        return "成功";
    }
}
